#include "bam_data.h"
#include "my_dir.h"
#include <string.h>
#include "sql_priv.h"
#include "sql_class.h"
Bam_data::Bam_data(void){
	this->bam_position = 0;
}

Bam_data::~Bam_data(void){
}

int Bam_data::open_bam(const char *path){
		b=bam_init1();
		bam_file = bam_open(path, "rb");


		if(bam_file == NULL)
			return -1;
		bam_header = bam_header_read(bam_file);
		this->block_address = bam_file->block_address;
		this->block_offset = bam_file->block_offset;
		return 0;

}
int Bam_data::reset_bam(){

	bam_file->block_address = this->get_block_address();
	bam_file->block_offset = this->get_block_offset();
	bam_file->block_length = this->get_block_length();


	//bam_header = bam_header_read(bam_file);

	return 0;

}

int Bam_data::get_block_length(){
	return this->bloc_length;
}

int Bam_data::close_bam(){
	if(this->bam_file == NULL)
		return -1;
	bam_close(this->bam_file);

	return 0;
}
int Bam_data::get_position(){

	return this->bam_position;
}

int64_t Bam_data::get_block_address(){

	return this->block_address;
}
  int Bam_data::get_block_offset(){

	  return this->block_offset;
  }
int Bam_data::set_position(int64_t block, int offset){

	this->bam_file->block_address = block;
	this->bam_file->block_offset = offset;
	return 0;
}

long Bam_data::get_row_count(){
	return this->row_count;
}
int Bam_data::reset_row_count(){
	row_count = 0;
	return 0;
}

int Bam_data::read_bam_alignment(TABLE *table, int position, unsigned char *buf){

	my_bitmap_map *old_map;
	if (row_count == 1)
		this->bloc_length= this->bam_file->block_length;
	char *sam_str;
	char *bam_field;
	Field *field;
	int read_bytes = bam_read1(bam_file,b);
	if (read_bytes > 0 )
	{
		old_map = dbug_tmp_use_all_columns(table, table->write_set);
		sam_str = bam_format1(bam_header,b);
		bam_field = strtok(sam_str, "\t");
		for (uint i = 0; i < table->s->fields; i++)
		{

			field = table->field[i];
			//my_ptrdiff_t offset;
			//offset = (my_ptrdiff_t) (buf - table->record[0]);
			//field->move_field_offset(offset);
			field->set_notnull();
			if (field->type() == MYSQL_TYPE_VARCHAR)
				field->store(bam_field,
					strlen(bam_field),
					field->charset());

			else /*if field->type() == MYSQL_TYPE_LONG || field->type() == MYSQL_TYPE_SHORT || field->type() == MYSQL_TYPE_INT24)*/
				field->store(atoi(bam_field),false);
			//field->move_field_offset(-offset);
			bam_field = strtok(NULL, "\t");
		}
		dbug_tmp_restore_column_map(table->write_set, old_map);
		this->row_count++;
		free(sam_str);
		return 0;
	}
	else
	{
		return 1;
	}

}
